import React, { useEffect, useState } from 'react';
import { NavBar, Image, Button, Tag, Space, Popup, List, Avatar, Badge } from 'antd-mobile';
import { 
    UserOutline, 
    ClockCircleOutline,
    TeamOutline,
    LeftOutline,
    StarOutline,
    MessageOutline
} from 'antd-mobile-icons';
import { history, useParams } from 'umi';
import styles from './index.less';
import { Toast } from 'antd-mobile';
import { useCourseStore } from '@/stores/courseStore';
import { courseAPI, CourseLevel, CourseLevelLabel } from '@/services/api';
import request from '@/utils/request';

interface CourseDetail {
    id: number;
    title: string;
    image: string;
    teacher: string;
    level: string;
    price: string;
    originalPrice: string;
    students: number;
    duration: string;
    maxStudents: number;
    schedule: string;
    description: string;
    features: string[];
    tags: string[];
}

interface CustomerService {
    id: number;
    username: string;
    real_name: string;
    avatar_url: string;
    status: 'online' | 'offline' | 'busy';
    last_active: string;
}

interface ApiResponse<T> {
    code: number;
    data: T;
}

const CourseDetail: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const [courseDetail, setCourseDetail] = useState<any>(null);
    const baseUrl = 'http://localhost:3001';
    const [showCustomerService, setShowCustomerService] = useState(false);
    const [customerServices, setCustomerServices] = useState<CustomerService[]>([]);

    useEffect(() => {
        const fetchCourseDetail = async () => {            
            try {
                const res = await courseAPI.getCourseDetail(Number(id));
                if (res.code === 200) {
                    setCourseDetail({
                        ...res.data,
                        image: `${baseUrl}${res.data.image_url}`,
                        level: CourseLevelLabel[res.data.level as CourseLevel],
                        teacher: res.data.teacher_name
                    });
                }
                console.log(res);
                
            } catch (error) {
                console.error('Failed to fetch course detail:', error);
            }
        };        
        if (id) {
            fetchCourseDetail();
        }
    }, [id]);

    // 获取客服列表
    const fetchCustomerServices = async () => {
        try {
            const res = await request.get<any, ApiResponse<CustomerService[]>>('/customer-service');
            if (res.code === 200) {
                setCustomerServices(res.data);
            }
        } catch (error) {
            console.error('Failed to fetch customer services:', error);
        }
    };

    // 处理咨询点击
    const handleConsult = (customerService: CustomerService) => {
        if (customerService.status !== 'online') {
            Toast.show({
                icon: 'fail',
                content: '该客服不在线',
            });
            return;
        }
        // TODO: 跳转到聊天页面
        history.push(`/chat/${customerService.id}`);
        setShowCustomerService(false);
    };

    if (!courseDetail) {
        return <div className={styles.loading}>加载中...</div>;
    }

    return (
        <div className={styles.container}>
            {/* 导航栏 */}
            <NavBar 
                className={styles.navbar}
                onBack={() => history.back()}
            >
                课程详情
            </NavBar>

            <div className={styles.content}>
                {/* 课程封面图 */}
                <div className={styles.courseImage}>
                    <img src={courseDetail.image} alt={courseDetail.title} />
                </div>

                {/* 课程基本信息 */}
                <div className={styles.courseInfo}>
                    <div className={styles.header}>
                        <h1 className={styles.title}>{courseDetail.title}</h1>
                        <div className={styles.tags}>
                            {courseDetail.tags.map((tag: string, index: number) => (
                                <Tag key={index} color='primary' className={styles.tag}>
                                    {tag}
                                </Tag>
                            ))}
                        </div>
                    </div>

                    <div className={styles.priceSection}>
                        <div className={styles.price}>
                            <span className={styles.symbol}>¥</span>
                            <span className={styles.amount}>{courseDetail.price}</span>
                            <span className={styles.originalPrice}>¥{courseDetail.original_price}</span>
                        </div>
                        <div className={styles.students}>
                            <TeamOutline /> {courseDetail.enrolled_students}人在学
                        </div>
                    </div>

                    {/* 课程信息列表 */}
                    <div className={styles.infoList}>
                        <div className={styles.infoItem}>
                            <UserOutline className={styles.icon} />
                            <span className={styles.label}>授课老师：</span>
                            <span className={styles.value}>{courseDetail.teacher}</span>
                        </div>
                        <div className={styles.infoItem}>
                            <ClockCircleOutline className={styles.icon} />
                            <span className={styles.label}>课程时长：</span>
                            <span className={styles.value}>{courseDetail.duration}</span>
                        </div>
                        <div className={styles.infoItem}>
                            <TeamOutline className={styles.icon} />
                            <span className={styles.label}>班级人数：</span>
                            <span className={styles.value}>限{courseDetail.max_students}人</span>
                        </div>
                    </div>

                    {/* 课程介绍 */}
                    <div className={styles.section}>
                        <h2 className={styles.sectionTitle}>课程介绍</h2>
                        <p className={styles.description}>{courseDetail.description}</p>
                    </div>

                    {/* 课程特色 */}
                    <div className={styles.section}>
                        <h2 className={styles.sectionTitle}>课程特色</h2>
                        <div className={styles.features}>
                            {courseDetail.features?.map((feature: string, index: number) => (
                                <div key={index} className={styles.featureItem}>
                                    <StarOutline className={styles.featureIcon} />
                                    {feature}
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>

            {/* 底部操作栏 */}
            <div className={styles.footer}>
                <Space className={styles.actions}>
                    <Button
                        className={styles.consultButton}
                        onClick={() => {
                            setShowCustomerService(true);
                            fetchCustomerServices();
                        }}
                    >
                        <MessageOutline /> 在线咨询
                    </Button>
                    <Button 
                        color='primary' 
                        className={styles.bookBtn}
                        onClick={() => {
                            console.log('预约');
                        }}
                    >
                        立即预约
                    </Button>
                </Space>
            </div>

            <Popup
                visible={showCustomerService}
                onMaskClick={() => setShowCustomerService(false)}
                bodyStyle={{
                    borderTopLeftRadius: '12px',
                    borderTopRightRadius: '12px',
                    minHeight: '40vh',
                }}
            >
                <div className={styles.customerServicePopup}>
                    <div className={styles.popupHeader}>
                        在线客服
                    </div>
                    <List className={styles.customerServiceList}>
                        {customerServices.map(cs => (
                            <List.Item
                                key={cs.id}
                                prefix={
                                    <Badge
                                        color={cs.status === 'online' ? '#00b578' : '#999'}
                                        className={styles.statusBadge}
                                    >
                                        <Avatar
                                            src={cs.avatar_url}
                                            className={styles.avatar}
                                        />
                                    </Badge>
                                }
                                description={cs.status === 'online' ? '在线' : '离线'}
                                onClick={() => handleConsult(cs)}
                                arrow={cs.status === 'online'}
                                className={cs.status !== 'online' ? styles.disabled : ''}
                            >
                                {cs.real_name}
                            </List.Item>
                        ))}
                    </List>
                </div>
            </Popup>
        </div>
    );
};

export default CourseDetail; 